/*
 * @Author: fangquan
 * @Date: 2020-6-19 10:00:00
 * @Last Modified by: fangquan
 * @Last Modified time: 2020-6-19 10:00:00 
 * @Usage 创建App 方法（主要为了成功授权之后再一步Mount）
 */


import store from "../store/index";
import device from "./device";

import { formatParams } from "./common";

import {
  getAccessToken,
  getAppId,
  getUserInfo,
  getUserAllInfo,
  writeCookie,
} from "@/apis/common";

import { weiboLogin } from "@/apis/python/index";

const NEED_REDIRECT = formatParams().unauth != 1 && device.wechat;
const GET_CODE = formatParams().getCode == 1 && formatParams().code;

/**
 * 获取access_token
 */
let requestAccessToken = () => {
  return new Promise((resolve) => {
    let params = {
      access_token:
        process.env.VUE_APP_TYPE == "development"
          ? "ebc5fd31-be5b-48d0-a938-cf51ac9008a4"
          : store.state.access_token,
    };

    getAccessToken(params).then((res) => {
      let { code, data } = res;

      if (code == 200) {
        console.log("---- 获取access_token成功 ----");
        store.commit("SET_ACCESS_TOKEN", data.token);

        resolve(res);
      }
    });
  });
};

/**
 * 获取AppId
 */
let requestAppId = () => {
  return new Promise((resolve) => {
    let params = {
      accId: formatParams().accId || 1,
      access_token: store.state.access_token
    }

    getAppId(params).then((res) => {
      let { code, data } = res;

      if (code == 200) {
        console.log("---- 获取AppId成功 ----");
        store.commit('SET_APP_ID', data.appid);

        resolve(res);
      }
    })
  })
}

/**
 * 获取用户信息
 */
let requestUserInfo = () => {
  return new Promise((resolve) => {
    let query = formatParams();

    if (GET_CODE) return console.log(`未使用过的code：${query.code}`);

    let params = {
      accid: query.accid || 1,
      code: query.code || "",
      access_token: store.state.access_token
    }

    getUserInfo(params).then((res) => {
      let { code } = res;

      if (code == 200 || ! NEED_REDIRECT) {
        if (code == 200) {
          console.log("---- 获取用户信息成功 ----");
          resolve(res);
        }
      }
    })
  })
}

/**
 * 获取所有用户信息
 */
let requestUserAllInfo = () => {
  return new Promise((resolve) => {
    let params = {
      access_token: store.state.access_token
    };

    getUserAllInfo(params).then((res) => {
      let { code, data } = res;

      if (code == 200 || !NEED_REDIRECT) {
        if (data) {
          console.log("---- 获取用户所有信息成功 ----");
          store.commit('SET_USER_INFO', data || {});
        }
        resolve(res);
      }
    })
  })
}

/**
 * 微博授权登录
 */
let requestWeiBoLogin = () => {
  return new Promise((resolve) => {
    let query = formatParams();

    if (GET_CODE) return console.log(`未使用过的code：${query.code}`);

    let params = {
      code: query.code || ""
    }

    if (query.inviterId) params.inviter = query.inviterId;

    weiboLogin(params).then((res) => {
      let { code, data } = res;

      if (code == 200 || !NEED_REDIRECT) {
        if (data) {
          console.log("---- 微博授权登录成功 ----");
          store.commit('SET_USER_INFO', data);
        }

        resolve(res);
      }
    })
  })
}

/**
 * 公共参数cookie
 */
let requestwriteCookie = () => {
  return new Promise((resolve) => {
    let params = {
      brandType: 1,
      clientType: 1,
      clientVersion: 1
    }

    writeCookie(params).then((res) => {
      let { code, data } = res;

      if (code == 200) {
        resolve(res);
      }
    })
  })
}

/**
 * 对外暴露的创建App方法
 */
export default async () => {
  if (formatParams().unauth == 1) {
    // 免授权
    await requestAccessToken();
    await requestwriteCookie();
  } else if (location.href.match("/mobile/think")) {
    // 巴巴思维页面授权登录
    await requestThinkAccessToken();
    await requestAppId();
    await requestThinkLogin();
  } else if (device.weibo) {
    // 微博授权登录
    await requestWeiBoLogin();
  } else {
    // 普通的微信授权登录
    await requestAccessToken();
    await requestAppId();
    await requestUserInfo();
    await requestUserAllInfo();
    await requestwriteCookie();
  }
}